package com.ruoyi.tb.lmt.controller;

import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.Map;

import cn.dev33.satoken.annotation.SaIgnore;
import com.google.api.client.util.SecurityUtils;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.tb.lmt.domain.TbRepairplanlist;
import com.ruoyi.tb.lmt.domain.bo.TbLocomotiveBo;
import com.ruoyi.tb.lmt.domain.bo.TbMessageNoticeBo;
import com.ruoyi.tb.lmt.domain.bo.TbRepairplanlistApprovedBo;
import com.ruoyi.tb.lmt.domain.vo.TbLmtrepairWorkdetailVo;
import com.ruoyi.tb.lmt.service.*;
import lombok.RequiredArgsConstructor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;

import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.tb.lmt.domain.vo.TbRepairplanlistVo;
import com.ruoyi.tb.lmt.domain.bo.TbRepairplanlistBo;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 计划明细
 *
 * @author ruoyi
 * @date 2023-12-07
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xha-lmt/repairplanlist")
public class TbRepairplanlistController extends BaseController {

    private final ITbRepairplanlistService iTbRepairplanlistService;

    @Autowired
    private ITbRepairplanlistApprovedService iTbRepairplanlistApprovedService;

    @Autowired
    private ITbMessageNoticeService iTbMessageNoticeService;


    @Autowired
    private ITbLmtrepairWorkdetailService iTbLmtrepairWorkdetailService;

    @Autowired
    private ITbLocomotiveService tbLocomotiveService;

    /**
     * 查询计划明细列表
     */
    @SaCheckPermission("xha-lmt:repairplanlist:list")
    @GetMapping("/list")
    public TableDataInfo<TbRepairplanlistVo> list(TbRepairplanlistBo bo, PageQuery pageQuery) {
        return iTbRepairplanlistService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询带创建工作列表
     */

    @GetMapping("/todoList")
    public TableDataInfo<TbRepairplanlistVo> todoList(TbRepairplanlistBo bo, PageQuery pageQuery) {
        return iTbRepairplanlistService.todoList(bo, pageQuery);
    }

    /**
     * 导出计划明细列表
     */
    @SaCheckPermission("xha-lmt:repairplanlist:export")
    @Log(title = "计划明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TbRepairplanlistBo bo, HttpServletResponse response) {
        List<TbRepairplanlistVo> list = iTbRepairplanlistService.queryList(bo);
        ExcelUtil.exportExcel(list, "计划明细", TbRepairplanlistVo.class, response);
    }

    /**
     * 获取计划明细详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("xha-lmt:repairplanlist:query")
    @GetMapping("/{id}")
    public R<TbRepairplanlistVo> getInfo(@NotNull(message = "主键不能为空")
                                         @PathVariable Long id) {
        return R.ok(iTbRepairplanlistService.queryById(id));
    }

    /**
     * 新增计划明细
     */
    @SaCheckPermission("xha-lmt:repairplanlist:add")
    @Log(title = "计划明细", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TbRepairplanlistBo bo) {
        return toAjax(iTbRepairplanlistService.insertByBo(bo));
    }

    /**
     * 修改计划明细
     */
    @SaCheckPermission("xha-lmt:repairplanlist:edit")
    @Log(title = "计划明细", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TbRepairplanlistBo bo) {
        bo.setRepairType(bo.getRepairChar());
        TbRepairplanlistVo vo = iTbRepairplanlistService.queryById(bo.getId());
        if (!vo.getRepairChar().equals(bo.getRepairChar())) {
            iTbLmtrepairWorkdetailService.deleteByLmtRepairId(bo.getId());
            iTbLmtrepairWorkdetailService.startByBo(bo);
        }
      /*  TbLocomotiveBo tbLocomotiveBo = new TbLocomotiveBo();
        tbLocomotiveBo.setLmtNumber(bo.getLmtNumber());
        tbLocomotiveBo.setRepairNum(bo.getRepairNum());
        tbLocomotiveBo.setLastRepairChar(bo.getRepairType());
        if (bo.getStartTime()!=null){
            tbLocomotiveBo.setNextPlanRepairDate(DateUtils.addDays(bo.getStartTime(), 183));
            tbLocomotiveBo.setNjRepairDate(bo.getStartTime());
        }else {
            tbLocomotiveBo.setNextPlanRepairDate(DateUtils.addDays(DateUtils.getNowDate(), 183));
            tbLocomotiveBo.setNjRepairDate(DateUtils.getNowDate());
        }
        tbLocomotiveService.updateByBoLmtNumber(tbLocomotiveBo);*/
        return toAjax(iTbRepairplanlistService.updateByBo(bo));
    }

    /**
     * 删除计划明细
     *
     * @param ids 主键串
     */
    @SaCheckPermission("xha-lmt:repairplanlist:remove")
    @Log(title = "计划明细", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iTbRepairplanlistService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    //查询满足条件的List集合
    @GetMapping("/list/condition")
    public R<List<TbRepairplanlistVo>> listCondition(String searchText, String planName, String workGroup) {
        return R.ok(iTbRepairplanlistService.selectStartList(searchText, planName, workGroup));
    }

    //查询工队派活的左侧大机List集合
    @GetMapping("/list/conditionSecond")
    public R<List<TbRepairplanlistVo>> listConditionSecond(String searchText, String planName, String workGroup) {
        return R.ok(iTbRepairplanlistService.selectSecondList(searchText, planName, workGroup));
    }


    //查询维修任务的左侧大机List集合
    @GetMapping("/list/conditionOverhaul")
    public R<List<TbRepairplanlistVo>> listConditionOverhaul(String searchText, String planName, String workGroup) {
        return R.ok(iTbRepairplanlistService.selectOverhaulList(searchText, planName, workGroup));
    }


    //遗留问题的左侧大机List集合
    @GetMapping("/list/conditionLegacy")
    public R<List<TbRepairplanlistVo>> listConditionLegacy(String searchText, String planName, String workGroup) {
        return R.ok(iTbRepairplanlistService.selectLegacyList(searchText, planName, workGroup));
    }

    //过程检查的左侧大机List集合
    @GetMapping("/list/conditionCheck")
    public R<List<TbRepairplanlistVo>> listConditionCheck(String searchText, String planName, String workGroup) {
        return R.ok(iTbRepairplanlistService.selectCheckList(searchText, planName, workGroup));
    }

    //过程验收的左侧大机List集合
    @GetMapping("/list/conditionApproval")
    public R<List<TbRepairplanlistVo>> listConditionApproval(String searchText, String planName, String workGroup) {
        return R.ok(iTbRepairplanlistService.selectApprovalList(searchText, planName, workGroup));
    }

    //大机履历具体车号历史计划明细
    @GetMapping("/list/historyLocomotive")
    public TableDataInfo<TbRepairplanlistVo> listHistoryLocomotive(String lmtType, String lmtNumber, String workerTeam, String planCode, String planName, String repairChar, String repairStartDate, String repairEndDate, PageQuery pageQuery) {
        return iTbRepairplanlistService.selectLocomotiveList(lmtType, lmtNumber, workerTeam, planCode, planName, repairChar, repairStartDate, repairEndDate, pageQuery);
    }

    //导出检修记录
    @SaIgnore
    @PostMapping("/list/historyLocomotive/{id}")
    public ResponseEntity<byte[]> historyLocomotive(@NotNull(message = "主键不能为空")
                                                        @PathVariable Long id) {
        TbRepairplanlistVo tbRepairplanlistVo = iTbRepairplanlistService.queryById(id);
        List<TbLmtrepairWorkdetailVo> tbLmtrepairWorkdetailVos = iTbLmtrepairWorkdetailService.queryByLmtRepairId(id);
        return iTbRepairplanlistService.createWord(tbRepairplanlistVo,tbLmtrepairWorkdetailVos);
    }

    //根据车型车号查询计划明细id，返回id
    @GetMapping("/list/planId")
    public R<Long> listPlanId(String lmtType, String lmtNumber) {
        return R.ok(iTbRepairplanlistService.selectPlanId(lmtType, lmtNumber));
    }

    //查询互检的List集合
    @GetMapping("/list/Mutual")
    public R<List<TbRepairplanlistVo>> listMutual(String searchText) {
        return R.ok(iTbRepairplanlistService.selectMutualList(searchText));
    }

    //查询专检的List集合
    @GetMapping("/list/special")
    public R<List<TbRepairplanlistVo>> listSpecial(String searchText) {
        return R.ok(iTbRepairplanlistService.selectSpecialList(searchText));
    }

    //查询验收的List集合
    @GetMapping("/list/Acceptance")
    public R<List<TbRepairplanlistVo>> listAcceptance(String searchText) {
        return R.ok(iTbRepairplanlistService.selectAcceptanceList(searchText));
    }

    //大机信息详情中的历史修程信息
    @GetMapping("/list/historyDetail")
    public TableDataInfo<TbRepairplanlistVo> listHistoryDetail(String lmtType, String lmtNumber, PageQuery pageQuery) {
        return iTbRepairplanlistService.selectHistoryDetailList(lmtType, lmtNumber, pageQuery);
    }

    //导入模板
    @SaCheckPermission("xha-lmt:repairplanlist:exportPlan")
    @RequestMapping(value = "/excel/export")
    public void export(HttpServletRequest request, HttpServletResponse response) {
        iTbRepairplanlistService.export(request, response);
    }

    //批量导入
    @SaCheckPermission("xha-lmt:repairplanlist:update")
    @PostMapping(value = "/excel/update")
    public R<Map<String, Object>> updateExcel(@RequestPart("file") MultipartFile file) throws Exception {
        return R.ok(iTbRepairplanlistService.updateExcel(file));
    }

    //大机履历报告申请按钮
    @SaCheckPermission("xha-lmt:repairplanlist:approved")
    @PutMapping("/approved")
    public R<Void> approved(@Validated(EditGroup.class) @RequestBody TbRepairplanlistBo bo) {

        //修改明细表
        bo.setApprovedStatus("审批中");
        LoginUser currentUser = LoginHelper.getLoginUser();
        bo.setApplicant(currentUser.getUsername());

        //添加到申请表中
        TbRepairplanlistApprovedBo approvedBo = new TbRepairplanlistApprovedBo();
        approvedBo.setApprovedId(bo.getId());
        if (bo.getPlanId() != null) approvedBo.setPlanId(bo.getPlanId());
        if (bo.getLmtNumber() != null) approvedBo.setLmtNumber(bo.getLmtNumber());
        if (bo.getLmtType() != null) approvedBo.setLmtType(bo.getLmtType());
        if (bo.getRepairType() != null) approvedBo.setRepairType(bo.getRepairType());
        if (bo.getRepairTimes() != null) approvedBo.setRepairTimes(bo.getRepairTimes());
        if (bo.getRepairChar() != null) approvedBo.setRepairChar(bo.getRepairChar());
        if (bo.getRepairCode() != null) approvedBo.setRepairCode(bo.getRepairCode());
        if (bo.getCheckUser2() != null) approvedBo.setCheckUser2(bo.getCheckUser2());
        if (bo.getCheckUser3() != null) approvedBo.setCheckUser3(bo.getCheckUser3());
        if (bo.getWorkerTeam() != null) approvedBo.setWorkerTeam(bo.getWorkerTeam());
        if (bo.getWorkGroup() != null) approvedBo.setWorkGroup(bo.getWorkGroup());
        if (bo.getWorkGroupId() != null) approvedBo.setWorkGroupId(bo.getWorkGroupId());
        approvedBo.setApplicant(currentUser.getUsername());
        approvedBo.setApprovedStatus("设备科审批中");
        //todo 设置审批人
        //设备科负责人
        approvedBo.setApprovedUser(iTbMessageNoticeService.getEquipmentDepartment());
        iTbRepairplanlistApprovedService.insertByBo(approvedBo);
        //发送消息通知
        TbMessageNoticeBo messageNoticeBo = new TbMessageNoticeBo();
        messageNoticeBo.setMessageId(bo.getId());
        messageNoticeBo.setMessageTitle(bo.getLmtNumber() + "申请履历报告");
        messageNoticeBo.setMessageName(currentUser.getUsername() + "申请" + bo.getLmtNumber() + "大机的履历报告，请及时处理。");
        messageNoticeBo.setMessageType("申请履历报告");
        messageNoticeBo.setLmtType(bo.getLmtType());
        messageNoticeBo.setLmtNumber(bo.getLmtNumber());
        messageNoticeBo.setWorkGroup(currentUser.getDeptName());
        messageNoticeBo.setWorkUser(currentUser.getUsername());
        messageNoticeBo.setWorkerTeam(bo.getWorkerTeam());
        messageNoticeBo.setStatus("0");
        messageNoticeBo.setWorkGroupId(bo.getWorkGroupId());
        messageNoticeBo.setWorkTime(new Date());
        //设置接收人为设备科负责人
        messageNoticeBo.setRecipient(iTbMessageNoticeService.getEquipmentDepartment());
        iTbMessageNoticeService.insertByBo(messageNoticeBo);

        return toAjax(iTbRepairplanlistService.updateByBo(bo));
    }
}
